<a href="http://github.com/angular/angular.js/edit/master/docs/content/guide/directive.ngdoc" class="improve-docs btn btn-primary"><i class="icon-edit"> </i> Improve this doc</a><h1><code ng:non-bindable=""></code>
<div><span class="hint"></span>
</div>
</h1>
<div><div class="directives-page"><h2 id="creating-custom-directives">Creating Custom Directives</h2>
<div class="alert alert-warning">
<strong>Note:</strong> this guide is targeted towards developers who are already familiar with AngularJS basics.
If you&#39;re just getting started, we recommend the <a href="tutorial/index">tutorial</a> first.
If you&#39;re looking for the <strong>directives API</strong>, we recently moved it to <a href="api/ng.$compile"><code><code>$compile</code></code></a>.
</div>


<p>This document explains when you&#39;d want to create your own directives in your AngularJS app, and
how to implement them.</p>
<h3 id="creating-custom-directives_what-are-directives">What are Directives?</h3>
<p>At a high level, directives are markers on a DOM element (such as an attribute, element
name, or CSS class) that tell AngularJS&#39;s <strong>HTML compiler</strong> (<a href="api/ng.$compile"><code><code>$compile</code></code></a>) to
attach a specified behavior to that DOM element or even transform the DOM element and its children.</p>
<p>Angular comes with a set of these directives built-in, like <code>ngBind</code>, <code>ngModel</code>, and <code>ngView</code>.
Much like you create controllers and services, you can create your own directives for Angular to use.
When Angular <a href="guide/bootstrap">bootstraps</a> your application, the
<a href="guide/compiler">HTML compiler</a> traverses the DOM matching directives against the DOM elements.</p>
<div class="alert alert-info">
<strong>What does it mean to &quot;compile&quot; an HTML template?</strong>

For AngularJS, &quot;compilation&quot; means attaching event listeners to the HTML to make it interactive.
The reason we use the term &quot;compile&quot; is that the recursive process of attaching directives
mirrors the process of compiling source code in
<a href="http://en.wikipedia.org/wiki/Compiled_languages">compiled programming languages</a>.
</div>


<h3 id="creating-custom-directives_matching-directives">Matching Directives</h3>
<p>Before we can write a directive, we need to know how Angular&#39;s <a href="guide/compiler">HTML compiler</a>
determines when to use a given directive.</p>
<p>In the following example, we say that the <code>&lt;input&gt;</code> element <strong>matches</strong> the <code>ngModel</code> directive.</p>
<pre><code class="lang-javascript">&lt;input ng-model=&quot;foo&quot;&gt;</code></pre>
<p>The following also <strong>matches</strong> <code>ngModel</code>:</p>
<pre><code class="lang-javascript">&lt;input data-ng:model=&quot;foo&quot;&gt;</code></pre>
<p>Angular <strong>normalizes</strong> an element&#39;s tag and attribute name to determine which elements match which
directives. We typically refer to directives by their case-sensitive
<a href="http://en.wikipedia.org/wiki/CamelCase">camelCase</a> <strong>normalized</strong> name (e.g. <code>ngModel</code>). 
However, since HTML is case-insensitive, we refer to directives in the DOM by lower-case
forms, typically using <a href="http://en.wikipedia.org/wiki/Letter_case#Computers">dash-delimited</a>
attributes on DOM elements (e.g. <code>ng-model</code>).</p>
<p>The <strong>normalization</strong> process is as follows:</p>
<ol>
<li>Strip <code>x-</code> and <code>data-</code> from the front of the element/attributes.</li>
<li>Convert the <code>:</code>, <code>-</code>, or <code>_</code>-delimited name to <code>camelCase</code>.</li>
</ol>
<p>Here are some equivalent examples of elements that match <code>ngBind</code>:</p>
<h3 id="creating-custom-directives_source">Source</h3>
<div source-edit="docsBindExample" source-edit-deps="angular.js script.js" source-edit-html="index.html-226" source-edit-css="" source-edit-js="script.js-225" source-edit-json="" source-edit-unit="" source-edit-scenario="scenario.js-227" source-edit-protractor=""></div>
<div class="tabbable"><div class="tab-pane" title="index.html">
<pre class="prettyprint linenums" ng-set-text="index.html-226" ng-html-wrap="docsBindExample angular.js script.js"></pre>
<script type="text/ng-template" id="index.html-226">
    <div ng-controller="Ctrl1">
      Hello <input ng-model='name'> <hr/>
      <span ng-bind="name"></span> <br/>
      <span ng:bind="name"></span> <br/>
      <span ng_bind="name"></span> <br/>
      <span data-ng-bind="name"></span> <br/>
      <span x-ng-bind="name"></span> <br/>
    </div>
  </script>
</div>
<div class="tab-pane" title="script.js">
<pre class="prettyprint linenums" ng-set-text="script.js-225"></pre>
<script type="text/ng-template" id="script.js-225">
    angular.module('docsBindExample', [])
      .controller('Ctrl1', function Ctrl1($scope) {
        $scope.name = 'Max Karl Ernst Ludwig Planck (April 23, 1858 – October 4, 1947)';
      });
  </script>
</div>
<div class="tab-pane" title="ngScenario e2e test">
<pre class="prettyprint linenums" ng-set-text="scenario.js-227"></pre>
<script type="text/ng-template" id="scenario.js-227">
    it('should show off bindings', function() {
      expect(element('div[ng-controller="Ctrl1"] span[ng-bind]').text())
        .toBe('Max Karl Ernst Ludwig Planck (April 23, 1858 – October 4, 1947)');
    });
  </script>
</div>
</div><h3 id="creating-custom-directives_demo">Demo</h3>
<div class="well doc-example-live animate-container" ng-embed-app="docsBindExample" ng-set-html="index.html-226" ng-eval-javascript="script.js-225"></div>
<div class="alert alert-success">
<strong>Best Practice:</strong> Prefer using the dash-delimited format (e.g. <code>ng-bind</code> for <code>ngBind</code>).
If you want to use an HTML validating tool, you can instead use the <code>data</code>-prefixed version (e.g.
<code>data-ng-bind</code> for <code>ngBind</code>).
The other forms shown above are accepted for legacy reasons but we advise you to avoid them.
</div>

<p><code>$compile</code> can match directives based on element names, attributes, class names, as well as comments.</p>
<p>All of the Angular-provided directives match attribute name, tag name, comments, or class name.
The following demonstrates the various ways a directive (<code>myDir</code> in this case) can be referenced
from within a template:</p>
<pre><code class="lang-html">&lt;my-dir&gt;&lt;/my-dir&gt;
&lt;span my-dir=&quot;exp&quot;&gt;&lt;/span&gt;
&lt;!-- directive: my-dir exp --&gt;
&lt;span class=&quot;my-dir: exp;&quot;&gt;&lt;/span&gt;</code></pre>
<div class="alert alert-success">
<strong>Best Practice:</strong> Prefer using directives via tag name and attributes over comment and class names.
Doing so generally makes it easier to determine what directives a given element matches.
</div>

<div class="alert alert-success">
<strong>Best Practice:</strong> Comment directives were commonly used in places where the DOM API limits the
ability to create directives that spanned multiple elements (e.g. inside <code>&lt;table&gt;</code> elements).
AngularJS 1.2 introduces <a href="api/ng.directive:ngRepeat"><code><code>ng-repeat-start</code> and <code>ng-repeat-end</code></code></a>
as a better solution to this problem. Developers are encouraged to use this over custom comment
directives when possible.
</div>



<h4 id="creating-custom-directives_demo_text-and-attribute-bindings">Text and attribute bindings</h4>
<p>During the compilation process the <a href="api/ng.$compile"><code>compiler</code></a> matches text and attributes
using the <a href="api/ng.$interpolate"><code>$interpolate</code></a> service to see if they contain embedded
expressions. These expressions are registered as <a href="api/ng.$rootScope.Scope#methods_$watch"><code>watches</code></a>
and will update as part of normal <a href="api/ng.$rootScope.Scope#methods_$digest"><code>digest</code></a> cycle. An
example of interpolation is shown below:</p>
<pre><code class="lang-html">&lt;a ng-href=&quot;img/{{username}}.jpg&quot;&gt;Hello {{username}}!&lt;/a&gt;</code></pre>
<h4 id="creating-custom-directives_demo_-attribute-bindings"><code>ngAttr</code> attribute bindings</h4>
<p>Web browsers are sometimes picky about what values they consider valid for attributes.</p>
<p>For example, considering this template:</p>
<pre><code class="lang-html">&lt;svg&gt;
  &lt;circle cx=&quot;{{cx}}&quot;&gt;&lt;/circle&gt;
&lt;/svg&gt;</code></pre>
<p>We would expect Angular to be able to bind to this, but when we check the console we see
something like <code>Error: Invalid value for attribute cx=&quot;{{cx}}&quot;</code>. Because of the SVG DOM API&#39;s
restrictions, you cannot simply write <code>cx=&quot;{{cx}}&quot;</code>.</p>
<p>With <code>ng-attr-cx</code> you can work around this problem.</p>
<p>If an attribute with a binding is prefixed with the <code>ngAttr</code> prefix (denormalized as <code>ng-attr-</code>)
then during the binding will be applied to the corresponding unprefixed attribute. This allows
you to bind to attributes that would otherwise be eagerly processed by browsers
(e.g. an SVG element&#39;s <code>circle[cx]</code> attributes).</p>
<p>For example, we could fix the example above by instead writing:</p>
<pre><code class="lang-html">&lt;svg&gt;
  &lt;circle ng-attr-cx=&quot;{{cx}}&quot;&gt;&lt;/circle&gt;
&lt;/svg&gt;</code></pre>
<h3 id="creating-custom-directives_creating-directives">Creating Directives</h3>
<p>First let&#39;s talk about the API for registering directives. Much like controllers, directives are
registered on modules. To register a directive, you use the <code>module.directive</code> API.
<code>module.directive</code> takes the
<a href="guide/directive#creating-custom-directives_matching-directives">normalized</a> directive name
followed by a <strong>factory function.</strong> This factory function should return an object with the different
options to tell <code>$compile</code> how the directive should behave when matched.</p>
<p>The factory function is invoked only once when the
<a href="api/ng.$compile"><code>compiler</code></a> matches the directive for the first time. You can perform any
initialization work here. The function is invoked using
<a href="api/AUTO.$injector#methods_invoke"><code>$injector.invoke</code></a> which makes it injectable just like a
controller.</p>
<div class="alert alert-success">
<strong>Best Practice:</strong> Prefer using the definition object over returning a function.
</div>


<p>We&#39;ll go over a few common examples of directives, then dive deep into the different options
and compilation process.</p>
<div class="alert alert-success">
<strong>Best Practice:</strong> In order to avoid collisions with some future standard, it&#39;s best to prefix your own
directive names. For instance, if you created a <code>&lt;carousel&gt;</code> directive, it would be problematic if HTML7
introduced the same element. A two or three letter prefix (e.g. <code>btfCarousel</code>) works well. Similarly, do
not prefix your own directives with <code>ng</code> or they might conflict with directives included in a future
version of Angular.
</div>

<p>For the following examples, we&#39;ll use the prefix <code>my</code> (e.g. <code>myCustomer</code>).</p>
<h4 id="creating-custom-directives_creating-directives_template-expanding-directive">Template-expanding directive</h4>
<p>Let&#39;s say you have a chunk of your template that represents a customer&#39;s information. This template
is repeated many times in your code. When you change it in one place, you have to change it in
several others. This is a good opportunity to use a directive to simplify your template.</p>
<p>Let&#39;s create a directive that simply replaces its contents with a static template:</p>
<h3 id="creating-custom-directives_source">Source</h3>
<div source-edit="docsSimpleDirective" source-edit-deps="angular.js script.js" source-edit-html="index.html-229" source-edit-css="" source-edit-js="script.js-228" source-edit-json="" source-edit-unit="" source-edit-scenario="" source-edit-protractor=""></div>
<div class="tabbable"><div class="tab-pane" title="index.html">
<pre class="prettyprint linenums" ng-set-text="index.html-229" ng-html-wrap="docsSimpleDirective angular.js script.js"></pre>
<script type="text/ng-template" id="index.html-229">
    <div ng-controller="Ctrl">
      <div my-customer></div>
    </div>
  </script>
</div>
<div class="tab-pane" title="script.js">
<pre class="prettyprint linenums" ng-set-text="script.js-228"></pre>
<script type="text/ng-template" id="script.js-228">
    angular.module('docsSimpleDirective', [])
      .controller('Ctrl', function($scope) {
        $scope.customer = {
          name: 'Naomi',
          address: '1600 Amphitheatre'
        };
      })
      .directive('myCustomer', function() {
        return {
          template: 'Name: {{customer.name}} Address: {{customer.address}}'
        };
      });
  </script>
</div>
</div><h3 id="creating-custom-directives_demo">Demo</h3>
<div class="well doc-example-live animate-container" ng-embed-app="docsSimpleDirective" ng-set-html="index.html-229" ng-eval-javascript="script.js-228"></div>
<p>Notice that we have bindings in this directive. After <code>$compile</code> compiles and links
<code>&lt;div my-customer&gt;
&lt;/div&gt;</code>, it will try to match directives on the element&#39;s children. This means you
can compose directives of other directives. We&#39;ll see how to do that in
<a href="guide/directive#creating-custom-directives_demo_creating-directives-that-communicate">an example</a>
below.</p>
<p>In the example above we in-lined the value of the <code>template</code> option, but this will become annoying
as the size of your template grows.</p>
<div class="alert alert-success">
<strong>Best Practice:</strong> Unless your template is very small, it&#39;s typically better to break it apart into
its own HTML file and load it with the <code>templateUrl</code> option.
</div>

<p>If you are familiar with <code>ngInclude</code>, <code>templateUrl</code> works just like it. Here&#39;s the same example
using <code>templateUrl</code> instead:</p>
<h3 id="creating-custom-directives_source">Source</h3>
<div source-edit="docsTemplateUrlDirective" source-edit-deps="angular.js script.js" source-edit-html="index.html-231 my-customer.html" source-edit-css="" source-edit-js="script.js-230" source-edit-json="" source-edit-unit="" source-edit-scenario="" source-edit-protractor=""></div>
<div class="tabbable"><div class="tab-pane" title="index.html">
<pre class="prettyprint linenums" ng-set-text="index.html-231" ng-html-wrap="docsTemplateUrlDirective angular.js script.js"></pre>
<script type="text/ng-template" id="index.html-231">
    <div ng-controller="Ctrl">
      <div my-customer></div>
    </div>
  </script>
</div>
<div class="tab-pane" title="my-customer.html">
<pre class="prettyprint linenums" ng-set-text="my-customer.html"></pre>
<script type="text/ng-template" id="my-customer.html">
    Name: {{customer.name}} Address: {{customer.address}}
  </script>
</div>
<div class="tab-pane" title="script.js">
<pre class="prettyprint linenums" ng-set-text="script.js-230"></pre>
<script type="text/ng-template" id="script.js-230">
    angular.module('docsTemplateUrlDirective', [])
      .controller('Ctrl', function($scope) {
        $scope.customer = {
          name: 'Naomi',
          address: '1600 Amphitheatre'
        };
      })
      .directive('myCustomer', function() {
        return {
          templateUrl: 'my-customer.html'
        };
      });
  </script>
</div>
</div><h3 id="creating-custom-directives_demo">Demo</h3>
<div class="well doc-example-live animate-container" ng-embed-app="docsTemplateUrlDirective" ng-set-html="index.html-231" ng-eval-javascript="script.js-230"></div>
<p>Great! But what if we wanted to have our directive match the tag name <code>&lt;my-customer&gt;</code> instead?
If we simply put a <code>&lt;my-customer&gt;</code> element into the HTML, it doesn&#39;t work.</p>
<div class="alert alert-waring">
<strong>Note:</strong> When you create a directive, it is restricted to attribute only by default. In order to
create directives that are triggered by element name, you need to use the <code>restrict</code> option.
</div>

<p>The <code>restrict</code> option is typically set to:</p>
<ul>
<li><code>&#39;A&#39;</code> - only matches attribute name</li>
<li><code>&#39;E&#39;</code> - only matches element name</li>
<li><code>&#39;AE&#39;</code> - matches either attribute or element name</li>
</ul>
<p>Let&#39;s change our directive to use <code>restrict: &#39;E&#39;</code>:</p>
<h3 id="creating-custom-directives_source">Source</h3>
<div source-edit="docsRestrictDirective" source-edit-deps="angular.js script.js" source-edit-html="index.html-233 my-customer.html" source-edit-css="" source-edit-js="script.js-232" source-edit-json="" source-edit-unit="" source-edit-scenario="" source-edit-protractor=""></div>
<div class="tabbable"><div class="tab-pane" title="index.html">
<pre class="prettyprint linenums" ng-set-text="index.html-233" ng-html-wrap="docsRestrictDirective angular.js script.js"></pre>
<script type="text/ng-template" id="index.html-233">
    <div ng-controller="Ctrl">
      <my-customer></my-customer>
    </div>
  </script>
</div>
<div class="tab-pane" title="my-customer.html">
<pre class="prettyprint linenums" ng-set-text="my-customer.html"></pre>
<script type="text/ng-template" id="my-customer.html">
    Name: {{customer.name}} Address: {{customer.address}}
  </script>
</div>
<div class="tab-pane" title="script.js">
<pre class="prettyprint linenums" ng-set-text="script.js-232"></pre>
<script type="text/ng-template" id="script.js-232">
    angular.module('docsRestrictDirective', [])
      .controller('Ctrl', function($scope) {
        $scope.customer = {
          name: 'Naomi',
          address: '1600 Amphitheatre'
        };
      })
      .directive('myCustomer', function() {
        return {
          restrict: 'E',
          templateUrl: 'my-customer.html'
        };
      });
  </script>
</div>
</div><h3 id="creating-custom-directives_demo">Demo</h3>
<div class="well doc-example-live animate-container" ng-embed-app="docsRestrictDirective" ng-set-html="index.html-233" ng-eval-javascript="script.js-232"></div>
<p>For more on the
<a href="api/ng.$compile#description_comprehensive-directive-api_directive-definition-object"><code><code>restrict</code></code></a>
property, see the
<a href="api/ng.$compile#description_comprehensive-directive-api_directive-definition-object"><code>API docs</code></a>.</p>
<div class="alert alert-info">
<strong>When should I use an attribute versus an element?</strong>

Use an element when you are creating a component that is in control of the template. The common case
for this is when you are creating a Domain-Specific Language for parts of your template.

Use an attribute when you are decorating an existing element with new functionality.
</div>

<p>Using an element for the <code>myCustomer</code> directive is clearly the right choice because you&#39;re not
decorating an element with some &quot;customer&quot; behavior; you&#39;re defining the core behavior of the
element as a customer component.</p>
<h4 id="creating-custom-directives_demo_isolating-the-scope-of-a-directive">Isolating the Scope of a Directive</h4>
<p>Our <code>myCustomer</code> directive above is great, but it has a fatal flaw. We can only use it once within a
given scope.</p>
<p>In its current implementation, we&#39;d need to create a different controller each time In order to
re-use such a directive:</p>
<h3 id="creating-custom-directives_source">Source</h3>
<div source-edit="docsScopeProblemExample" source-edit-deps="angular.js script.js" source-edit-html="index.html-235 my-customer.html" source-edit-css="" source-edit-js="script.js-234" source-edit-json="" source-edit-unit="" source-edit-scenario="" source-edit-protractor=""></div>
<div class="tabbable"><div class="tab-pane" title="index.html">
<pre class="prettyprint linenums" ng-set-text="index.html-235" ng-html-wrap="docsScopeProblemExample angular.js script.js"></pre>
<script type="text/ng-template" id="index.html-235">
    <div ng-controller="NaomiCtrl">
      <my-customer></my-customer>
    </div>
    <hr>
    <div ng-controller="IgorCtrl">
      <my-customer></my-customer>
    </div>
  </script>
</div>
<div class="tab-pane" title="my-customer.html">
<pre class="prettyprint linenums" ng-set-text="my-customer.html"></pre>
<script type="text/ng-template" id="my-customer.html">
    Name: {{customer.name}} Address: {{customer.address}}
  </script>
</div>
<div class="tab-pane" title="script.js">
<pre class="prettyprint linenums" ng-set-text="script.js-234"></pre>
<script type="text/ng-template" id="script.js-234">
    angular.module('docsScopeProblemExample', [])
      .controller('NaomiCtrl', function($scope) {
        $scope.customer = {
          name: 'Naomi',
          address: '1600 Amphitheatre'
        };
      })
      .controller('IgorCtrl', function($scope) {
        $scope.customer = {
          name: 'Igor',
          address: '123 Somewhere'
        };
      })
      .directive('myCustomer', function() {
        return {
          restrict: 'E',
          templateUrl: 'my-customer.html'
        };
      });
  </script>
</div>
</div><h3 id="creating-custom-directives_demo">Demo</h3>
<div class="well doc-example-live animate-container" ng-embed-app="docsScopeProblemExample" ng-set-html="index.html-235" ng-eval-javascript="script.js-234"></div>
<p>This is clearly not a great solution.</p>
<p>What we want to be able to do is separate the scope inside a directive from the scope
outside, and then map the outer scope to a directive&#39;s inner scope. We can do this by creating what
we call an <strong>isolate scope</strong>. To do this, we can use a directive&#39;s <code>scope</code> option:</p>
<h3 id="creating-custom-directives_source">Source</h3>
<div source-edit="docsIsolateScopeDirective" source-edit-deps="angular.js script.js" source-edit-html="index.html-237 my-customer-iso.html" source-edit-css="" source-edit-js="script.js-236" source-edit-json="" source-edit-unit="" source-edit-scenario="" source-edit-protractor=""></div>
<div class="tabbable"><div class="tab-pane" title="index.html">
<pre class="prettyprint linenums" ng-set-text="index.html-237" ng-html-wrap="docsIsolateScopeDirective angular.js script.js"></pre>
<script type="text/ng-template" id="index.html-237">
    <div ng-controller="Ctrl">
      <my-customer info="naomi"></my-customer>
      <hr>
      <my-customer info="igor"></my-customer>
    </div>
  </script>
</div>
<div class="tab-pane" title="my-customer-iso.html">
<pre class="prettyprint linenums" ng-set-text="my-customer-iso.html"></pre>
<script type="text/ng-template" id="my-customer-iso.html">
    Name: {{customerInfo.name}} Address: {{customerInfo.address}}
  </script>
</div>
<div class="tab-pane" title="script.js">
<pre class="prettyprint linenums" ng-set-text="script.js-236"></pre>
<script type="text/ng-template" id="script.js-236">
    angular.module('docsIsolateScopeDirective', [])
      .controller('Ctrl', function($scope) {
        $scope.naomi = { name: 'Naomi', address: '1600 Amphitheatre' };
        $scope.igor = { name: 'Igor', address: '123 Somewhere' };
      })
      .directive('myCustomer', function() {
        return {
          restrict: 'E',
          scope: {
            customerInfo: '=info'
          },
          templateUrl: 'my-customer-iso.html'
        };
      });
  </script>
</div>
</div><h3 id="creating-custom-directives_demo">Demo</h3>
<div class="well doc-example-live animate-container" ng-embed-app="docsIsolateScopeDirective" ng-set-html="index.html-237" ng-eval-javascript="script.js-236"></div>
<p>Looking at <code>index.html</code>, the first <code>&lt;my-customer&gt;</code> element binds the <code>info</code> attribute to <code>naomi</code>,
which we have exposed on our controller&#39;s scope. The second binds <code>info</code> to <code>igor</code>.</p>
<p>Let&#39;s take a closer look at the scope option:</p>
<pre><code class="lang-javascript">//...
scope: {
  customerInfo: &#39;=info&#39;
},
//...</code></pre>
<p>The <strong>scope option</strong> is an object that contains a property for each isolate scope binding.  In this
case it has just one property:</p>
<ul>
<li>Its name (<code>customerInfo</code>) corresponds to the
directive&#39;s <strong>isolate scope</strong> property <code>customerInfo</code>.</li>
<li>Its value (<code>=info</code>) tells <code>$compile</code> to bind to the <code>info</code> attribute.</li>
</ul>
<div class="alert alert-warning">
<strong>Note:</strong> These <code>=attr</code> attributes in the <code>scope</code> option of directives are normalized just like
directive names. To bind to the attribute in <code>&lt;div bind-to-this=&quot;thing&quot;&gt;</code>, you&#39;d specify a binding
of <code>=bindToThis</code>.
</div>

<p>For cases where the attribute name is the same as the value you want to bind to inside the
directive&#39;s scope, you can use this shorthand syntax:</p>
<pre><code class="lang-javascript">...
scope: {
  // same as &#39;=customer&#39;
  customer: &#39;=&#39;
},
...</code></pre>
<p>Besides making it possible to bind different data to the scope inside a directive, using an isolated
scope has another effect.</p>
<p>We can show this by adding another property, <code>vojta</code>, to our scope and trying to access it from
within our directive&#39;s template:</p>
<h3 id="creating-custom-directives_source">Source</h3>
<div source-edit="docsIsolationExample" source-edit-deps="angular.js script.js" source-edit-html="index.html-239 my-customer-plus-vojta.html" source-edit-css="" source-edit-js="script.js-238" source-edit-json="" source-edit-unit="" source-edit-scenario="" source-edit-protractor=""></div>
<div class="tabbable"><div class="tab-pane" title="index.html">
<pre class="prettyprint linenums" ng-set-text="index.html-239" ng-html-wrap="docsIsolationExample angular.js script.js"></pre>
<script type="text/ng-template" id="index.html-239">
    <div ng-controller="Ctrl">
      <my-customer info="naomi"></my-customer>
    </div>
  </script>
</div>
<div class="tab-pane" title="my-customer-plus-vojta.html">
<pre class="prettyprint linenums" ng-set-text="my-customer-plus-vojta.html"></pre>
<script type="text/ng-template" id="my-customer-plus-vojta.html">
    Name: {{customerInfo.name}} Address: {{customerInfo.address}}
    <hr>
    Name: {{vojta.name}} Address: {{vojta.address}}
  </script>
</div>
<div class="tab-pane" title="script.js">
<pre class="prettyprint linenums" ng-set-text="script.js-238"></pre>
<script type="text/ng-template" id="script.js-238">
    angular.module('docsIsolationExample', [])
      .controller('Ctrl', function($scope) {
        $scope.naomi = { name: 'Naomi', address: '1600 Amphitheatre' };

        $scope.vojta = { name: 'Vojta', address: '3456 Somewhere Else' };
      })
      .directive('myCustomer', function() {
        return {
          restrict: 'E',
          scope: {
            customerInfo: '=info'
          },
          templateUrl: 'my-customer-plus-vojta.html'
        };
      });
  </script>
</div>
</div><h3 id="creating-custom-directives_demo">Demo</h3>
<div class="well doc-example-live animate-container" ng-embed-app="docsIsolationExample" ng-set-html="index.html-239" ng-eval-javascript="script.js-238"></div>
<p>Notice that <code>{{vojta.name}}</code> and <code>{{vojta.address}}</code> are empty, meaning they are undefined.
Although we defined <code>vojta</code> in the controller, it&#39;s not available within the directive.</p>
<p>As the name suggests, the <strong>isolate scope</strong> of the directive isolates everything except models that
you&#39;ve explicitly added to the <code>scope: {}</code> hash object. This is helpful when building reusable
components because it prevents a component from changing your model state except for the models
that you explicitly pass in.</p>
<div class="alert alert-warning">
<strong>Note:</strong> Normally, a scope prototypically inherits from its parent. An isolated scope does not.
See the <a href="guide/directive#creating-custom-directives_demo_isolating-the-scope-of-a-directive">&quot;Isolating the Scope of a Directive&quot;</a> section for more information about isolate scopes.
</div>

<div class="alert alert-success">
<strong>Best Practice:</strong> Use the <code>scope</code> option to create isolate scopes when making components that you
want to reuse throughout your app.
</div>


<h4 id="creating-custom-directives_demo_creating-a-directive-that-manipulates-the-dom">Creating a Directive that Manipulates the DOM</h4>
<p>In this example we will build a directive that displays the current time.
Once a second, it updates the DOM to reflect the current time.</p>
<p>Directives that want to modify the DOM typically use the <code>link</code> option.
<code>link</code> takes a function with the following signature, <code>function link(scope, element, attrs) { ... }</code>
where:</p>
<ul>
<li><code>scope</code> is an Angular scope object.</li>
<li><code>element</code> is the jqLite-wrapped element that this directive matches.</li>
<li><code>attrs</code> is an object with the normalized attribute names and their corresponding values.</li>
</ul>
<p>In our <code>link</code> function, we want to update the displayed time once a second, or whenever a user
changes the time formatting string that our directive binds to. We will use the <code>$interval</code> service
to call a handler on a regular basis. This is easier than using <code>$timeout</code> but also works better with
end 2 end testing, where we want to ensure that all $timeouts have completed before completing the test.
We also want to remove the <code>$interval</code> if the directive is deleted so we don&#39;t introduce a memory leak.</p>
<h3 id="creating-custom-directives_source">Source</h3>
<div source-edit="docsTimeDirective" source-edit-deps="angular.js script.js" source-edit-html="index.html-241" source-edit-css="" source-edit-js="script.js-240" source-edit-json="" source-edit-unit="" source-edit-scenario="" source-edit-protractor=""></div>
<div class="tabbable"><div class="tab-pane" title="index.html">
<pre class="prettyprint linenums" ng-set-text="index.html-241" ng-html-wrap="docsTimeDirective angular.js script.js"></pre>
<script type="text/ng-template" id="index.html-241">
    <div ng-controller="Ctrl2">
      Date format: <input ng-model="format"> <hr/>
      Current time is: <span my-current-time="format"></span>
    </div>
  </script>
</div>
<div class="tab-pane" title="script.js">
<pre class="prettyprint linenums" ng-set-text="script.js-240"></pre>
<script type="text/ng-template" id="script.js-240">
    angular.module('docsTimeDirective', [])
      .controller('Ctrl2', function($scope) {
        $scope.format = 'M/d/yy h:mm:ss a';
      })
      .directive('myCurrentTime', function($interval, dateFilter) {

        function link(scope, element, attrs) {
          var format,
              timeoutId;

          function updateTime() {
            element.text(dateFilter(new Date(), format));
          }

          scope.$watch(attrs.myCurrentTime, function(value) {
            format = value;
            updateTime();
          });

          element.on('$destroy', function() {
            $interval.cancel(timeoutId);
          });

          // start the UI update process; save the timeoutId for canceling
          timeoutId = $interval(function() {
            updateTime(); // update DOM
          }, 1000);
        }

        return {
          link: link
        };
      });
  </script>
</div>
</div><h3 id="creating-custom-directives_demo">Demo</h3>
<div class="well doc-example-live animate-container" ng-embed-app="docsTimeDirective" ng-set-html="index.html-241" ng-eval-javascript="script.js-240"></div>
<p>There are a couple of things to note here.
Just like the <code>module.controller</code> API, the function argument in <code>module.directive</code> is dependency
injected. Because of this, we can use <code>$interval</code> and <code>dateFilter</code> inside our directive&#39;s <code>link</code>
function.</p>
<p>We register an event <code>element.on(&#39;$destroy&#39;, ...)</code>. What fires this <code>$destroy</code> event?</p>
<p>There are a few special events that AngularJS emits. When a DOM node that has been compiled
with Angular&#39;s compiler is destroyed, it emits a <code>$destroy</code> event. Similarly, when an AngularJS
scope is destroyed, it broadcasts a <code>$destroy</code> event to listening scopes.</p>
<p>By listening to this event, you can remove event listeners that might cause memory leaks.
Listeners registered to scopes and elements are automatically cleaned up when they are destroyed,
but if you registered a listener on a service, or registered a listener on a DOM node that isn&#39;t
being deleted, you&#39;ll have to clean it up yourself or you risk introducing a memory leak.</p>
<div class="alert alert-success">
<strong>Best Practice:</strong> Directives should clean up after themselves. You can use
<code>element.on(&#39;$destroy&#39;, ...)</code> or <code>scope.$on(&#39;$destroy&#39;, ...)</code> to run a clean-up function when the
directive is removed.
</div>


<h4 id="creating-custom-directives_demo_creating-a-directive-that-wraps-other-elements">Creating a Directive that Wraps Other Elements</h4>
<p>We&#39;ve seen that you can pass in models to a directive using the isolate scope, but sometimes
it&#39;s desirable to be able to pass in an entire template rather than a string or an object.
Let&#39;s say that we want to create a &quot;dialog box&quot; component. The dialog box should be able to
wrap any arbitrary content.</p>
<p>To do this, we need to use the <code>transclude</code> option.</p>
<h3 id="creating-custom-directives_source">Source</h3>
<div source-edit="docsTransclusionDirective" source-edit-deps="angular.js script.js" source-edit-html="index.html-243 my-dialog.html" source-edit-css="" source-edit-js="script.js-242" source-edit-json="" source-edit-unit="" source-edit-scenario="" source-edit-protractor=""></div>
<div class="tabbable"><div class="tab-pane" title="index.html">
<pre class="prettyprint linenums" ng-set-text="index.html-243" ng-html-wrap="docsTransclusionDirective angular.js script.js"></pre>
<script type="text/ng-template" id="index.html-243">
    <div ng-controller="Ctrl">
      <my-dialog>Check out the contents, {{name}}!</my-dialog>
    </div>
  </script>
</div>
<div class="tab-pane" title="my-dialog.html">
<pre class="prettyprint linenums" ng-set-text="my-dialog.html"></pre>
<script type="text/ng-template" id="my-dialog.html">
    <div class="alert" ng-transclude>
    </div>
  </script>
</div>
<div class="tab-pane" title="script.js">
<pre class="prettyprint linenums" ng-set-text="script.js-242"></pre>
<script type="text/ng-template" id="script.js-242">
    angular.module('docsTransclusionDirective', [])
      .controller('Ctrl', function($scope) {
        $scope.name = 'Tobias';
      })
      .directive('myDialog', function() {
        return {
          restrict: 'E',
          transclude: true,
          templateUrl: 'my-dialog.html'
        };
      });
  </script>
</div>
</div><h3 id="creating-custom-directives_demo">Demo</h3>
<div class="well doc-example-live animate-container" ng-embed-app="docsTransclusionDirective" ng-set-html="index.html-243" ng-eval-javascript="script.js-242"></div>
<p>What does this <code>transclude</code> option do, exactly? <code>transclude</code> makes the contents of a directive with
this option have access to the scope <strong>outside</strong> of the directive rather than inside.</p>
<p>To illustrate this, see the example below. Notice that we&#39;ve added a <code>link</code> function in <code>script.js</code>
that redefines <code>name</code> as <code>Jeff</code>. What do you think the <code>{{name}}</code> binding will resolve to now?</p>
<h3 id="creating-custom-directives_source">Source</h3>
<div source-edit="docsTransclusionExample" source-edit-deps="angular.js script.js" source-edit-html="index.html-245 my-dialog.html" source-edit-css="" source-edit-js="script.js-244" source-edit-json="" source-edit-unit="" source-edit-scenario="" source-edit-protractor=""></div>
<div class="tabbable"><div class="tab-pane" title="index.html">
<pre class="prettyprint linenums" ng-set-text="index.html-245" ng-html-wrap="docsTransclusionExample angular.js script.js"></pre>
<script type="text/ng-template" id="index.html-245">
    <div ng-controller="Ctrl">
      <my-dialog>Check out the contents, {{name}}!</my-dialog>
    </div>
  </script>
</div>
<div class="tab-pane" title="my-dialog.html">
<pre class="prettyprint linenums" ng-set-text="my-dialog.html"></pre>
<script type="text/ng-template" id="my-dialog.html">
    <div class="alert" ng-transclude>
    </div>
  </script>
</div>
<div class="tab-pane" title="script.js">
<pre class="prettyprint linenums" ng-set-text="script.js-244"></pre>
<script type="text/ng-template" id="script.js-244">
    angular.module('docsTransclusionExample', [])
      .controller('Ctrl', function($scope) {
        $scope.name = 'Tobias';
      })
      .directive('myDialog', function() {
        return {
          restrict: 'E',
          transclude: true,
          scope: {},
          templateUrl: 'my-dialog.html',
          link: function (scope, element) {
            scope.name = 'Jeff';
          }
        };
      });
  </script>
</div>
</div><h3 id="creating-custom-directives_demo">Demo</h3>
<div class="well doc-example-live animate-container" ng-embed-app="docsTransclusionExample" ng-set-html="index.html-245" ng-eval-javascript="script.js-244"></div>
<p>Ordinarily, we would expect that <code>{{name}}</code> would be <code>Jeff</code>. However, we see in this example that
the <code>{{name}}</code> binding is still <code>Tobias</code>.</p>
<p>The <code>transclude</code> option changes the way scopes are nested. It makes it so that the <strong>contents</strong> of a
transcluded directive have whatever scope is outside the directive, rather than whatever scope is on
the inside. In doing so, it gives the contents access to the outside scope.</p>
<p>Note that if the directive did not create its own scope, then <code>scope</code> in <code>scope.name = &#39;Jeff&#39;;</code> would
reference the outside scope and we would see <code>Jeff</code> in the output.</p>
<p>This behavior makes sense for a directive that wraps some content, because otherwise you&#39;d have to
pass in each model you wanted to use separately. If you have to pass in each model that you want to
use, then you can&#39;t really have arbitrary contents, can you?</p>
<div class="alert alert-success">
<strong>Best Practice:</strong> only use <code>transclude: true</code> when you want to create a directive that wraps
arbitrary content.
</div>

<p>Next, we want to add buttons to this dialog box, and allow someone using the directive to bind their
own behavior to it.</p>
<h3 id="creating-custom-directives_source">Source</h3>
<div source-edit="docsIsoFnBindExample" source-edit-deps="angular.js script.js" source-edit-html="index.html-247 my-dialog-close.html" source-edit-css="" source-edit-js="script.js-246" source-edit-json="" source-edit-unit="" source-edit-scenario="" source-edit-protractor=""></div>
<div class="tabbable"><div class="tab-pane" title="index.html">
<pre class="prettyprint linenums" ng-set-text="index.html-247" ng-html-wrap="docsIsoFnBindExample angular.js script.js"></pre>
<script type="text/ng-template" id="index.html-247">
    <div ng-controller="Ctrl">
      <my-dialog ng-hide="dialogIsHidden" on-close="hideDialog()">
        Check out the contents, {{name}}!
      </my-dialog>
    </div>
  </script>
</div>
<div class="tab-pane" title="my-dialog-close.html">
<pre class="prettyprint linenums" ng-set-text="my-dialog-close.html"></pre>
<script type="text/ng-template" id="my-dialog-close.html">
    <div class="alert">
      <a href class="close" ng-click="close()">&times;</a>
      <div ng-transclude></div>
    </div>
  </script>
</div>
<div class="tab-pane" title="script.js">
<pre class="prettyprint linenums" ng-set-text="script.js-246"></pre>
<script type="text/ng-template" id="script.js-246">
    angular.module('docsIsoFnBindExample', [])
      .controller('Ctrl', function($scope, $timeout) {
        $scope.name = 'Tobias';
        $scope.hideDialog = function () {
          $scope.dialogIsHidden = true;
          $timeout(function () {
            $scope.dialogIsHidden = false;
          }, 2000);
        };
      })
      .directive('myDialog', function() {
        return {
          restrict: 'E',
          transclude: true,
          scope: {
            'close': '&onClose'
          },
          templateUrl: 'my-dialog-close.html'
        };
      });
  </script>
</div>
</div><h3 id="creating-custom-directives_demo">Demo</h3>
<div class="well doc-example-live animate-container" ng-embed-app="docsIsoFnBindExample" ng-set-html="index.html-247" ng-eval-javascript="script.js-246"></div>
<p>We want to run the function we pass by invoking it from the directive&#39;s scope, but have it run
in the context of the scope where its registered.</p>
<p>We saw earlier how to use <code>=prop</code> in the <code>scope</code> option, but in the above example, we&#39;re using
<code>&amp;prop</code> instead. <code>&amp;</code> bindings expose a function to an isolated scope allowing the isolated scope
to invoke it, but maintaining the original scope of the function. So when a user clicks the
<code>x</code> in the dialog, it runs <code>Ctrl</code>&#39;s <code>close</code> function.</p>
<div class="alert alert-success">
<strong>Best Practice:</strong> use <code>&amp;prop</code> in the <code>scope</code> option when you want your directive
to expose an API for binding to behaviors.
</div>


<h4 id="creating-custom-directives_demo_creating-a-directive-that-adds-event-listeners">Creating a Directive that Adds Event Listeners</h4>
<p>Previously, we used the <code>link</code> function to create a directive that manipulated its
DOM elements. Building upon that example, let&#39;s make a directive that reacts to events on
its elements.</p>
<p>For instance, what if we wanted to create a directive that lets a user drag an
element?</p>
<h3 id="creating-custom-directives_source">Source</h3>
<div source-edit="dragModule" source-edit-deps="angular.js script.js" source-edit-html="index.html-249" source-edit-css="" source-edit-js="script.js-248" source-edit-json="" source-edit-unit="" source-edit-scenario="" source-edit-protractor=""></div>
<div class="tabbable"><div class="tab-pane" title="index.html">
<pre class="prettyprint linenums" ng-set-text="index.html-249" ng-html-wrap="dragModule angular.js script.js"></pre>
<script type="text/ng-template" id="index.html-249">
    <span my-draggable>Drag ME</span>
  </script>
</div>
<div class="tab-pane" title="script.js">
<pre class="prettyprint linenums" ng-set-text="script.js-248"></pre>
<script type="text/ng-template" id="script.js-248">
    angular.module('dragModule', []).
      directive('myDraggable', function($document) {
        return function(scope, element, attr) {
          var startX = 0, startY = 0, x = 0, y = 0;

          element.css({
           position: 'relative',
           border: '1px solid red',
           backgroundColor: 'lightgrey',
           cursor: 'pointer'
          });

          element.on('mousedown', function(event) {
            // Prevent default dragging of selected content
            event.preventDefault();
            startX = event.pageX - x;
            startY = event.pageY - y;
            $document.on('mousemove', mousemove);
            $document.on('mouseup', mouseup);
          });

          function mousemove(event) {
            y = event.pageY - startY;
            x = event.pageX - startX;
            element.css({
              top: y + 'px',
              left:  x + 'px'
            });
          }

          function mouseup() {
            $document.unbind('mousemove', mousemove);
            $document.unbind('mouseup', mouseup);
          }
        }
      });
  </script>
</div>
</div><h3 id="creating-custom-directives_demo">Demo</h3>
<div class="well doc-example-live animate-container" ng-embed-app="dragModule" ng-set-html="index.html-249" ng-eval-javascript="script.js-248"></div>
<h4 id="creating-custom-directives_demo_creating-directives-that-communicate">Creating Directives that Communicate</h4>
<p>You can compose any directives by using them within templates.</p>
<p>Sometimes, you want a component that&#39;s built from a combination of directives.</p>
<p>Imagine you want to have a container with tabs in which the contents of the container correspond
to which tab is active.</p>
<h3 id="creating-custom-directives_source">Source</h3>
<div source-edit="docsTabsExample" source-edit-deps="angular.js script.js" source-edit-html="index.html-251 my-tabs.html my-pane.html" source-edit-css="" source-edit-js="script.js-250" source-edit-json="" source-edit-unit="" source-edit-scenario="" source-edit-protractor=""></div>
<div class="tabbable"><div class="tab-pane" title="index.html">
<pre class="prettyprint linenums" ng-set-text="index.html-251" ng-html-wrap="docsTabsExample angular.js script.js"></pre>
<script type="text/ng-template" id="index.html-251">
    <my-tabs>
      <my-pane title="Hello">
        <h5 id="creating-custom-directives_source_hello">Hello</h5>
        <p>Lorem ipsum dolor sit amet</p>
      </my-pane>
      <my-pane title="World">
        <h5 id="creating-custom-directives_source_world">World</h5>
        <em>Mauris elementum elementum enim at suscipit.</em>
        <p><a href ng-click="i = i + 1">counter: {{i || 0}}</a></p>
      </my-pane>
    </my-tabs>
  </script>
</div>
<div class="tab-pane" title="my-tabs.html">
<pre class="prettyprint linenums" ng-set-text="my-tabs.html"></pre>
<script type="text/ng-template" id="my-tabs.html">
    <div class="tabbable">
      <ul class="nav nav-tabs">
        <li ng-repeat="pane in panes" ng-class="{active:pane.selected}">
          <a href="" ng-click="select(pane)">{{pane.title}}</a>
        </li>
      </ul>
      <div class="tab-content" ng-transclude></div>
    </div>
  </script>
</div>
<div class="tab-pane" title="my-pane.html">
<pre class="prettyprint linenums" ng-set-text="my-pane.html"></pre>
<script type="text/ng-template" id="my-pane.html">
    <div class="tab-pane" ng-show="selected" ng-transclude>
    </div>
  </script>
</div>
<div class="tab-pane" title="script.js">
<pre class="prettyprint linenums" ng-set-text="script.js-250"></pre>
<script type="text/ng-template" id="script.js-250">
    angular.module('docsTabsExample', [])
      .directive('myTabs', function() {
        return {
          restrict: 'E',
          transclude: true,
          scope: {},
          controller: function($scope) {
            var panes = $scope.panes = [];

            $scope.select = function(pane) {
              angular.forEach(panes, function(pane) {
                pane.selected = false;
              });
              pane.selected = true;
            };

            this.addPane = function(pane) {
              if (panes.length == 0) {
                $scope.select(pane);
              }
              panes.push(pane);
            };
          },
          templateUrl: 'my-tabs.html'
        };
      })
      .directive('myPane', function() {
        return {
          require: '^myTabs',
          restrict: 'E',
          transclude: true,
          scope: {
            title: '@'
          },
          link: function(scope, element, attrs, tabsCtrl) {
            tabsCtrl.addPane(scope);
          },
          templateUrl: 'my-pane.html'
        };
      });
  </script>
</div>
</div><h3 id="creating-custom-directives_demo">Demo</h3>
<div class="well doc-example-live animate-container" ng-embed-app="docsTabsExample" ng-set-html="index.html-251" ng-eval-javascript="script.js-250"></div>
<p>The <code>myPane</code> directive has a <code>require</code> option with value <code>^myTabs</code>. When a directive uses this
option, <code>$compile</code> will throw an error unless the specified controller is found. The <code>^</code> prefix
means that this directive searches for the controller on its parents (without the <code>^</code> prefix, the
directive would look for the controller on just its own element).</p>
<p>So where does this <code>myTabs</code> controller come from? Directives can specify controllers using
the unsurprisingly named <code>controller</code> option. As you can see, the <code>myTabs</code> directive uses this
option. Just like <code>ngController</code>, this option attaches a controller to the template of the directive.</p>
<p>Looking back at <code>myPane</code>&#39;s definition, notice the last argument in its <code>link</code> function: <code>tabsCtrl</code>.
When a directive requires a controller, it receives that controller as the fourth argument of its
<code>link</code> function. Taking advantage of this, <code>myPane</code> can call the <code>addPane</code> function of <code>myTabs</code>.</p>
<p>Savvy readers may be wondering what the difference is between <code>link</code> and <code>controller</code>.
The basic difference is that <code>controller</code> can expose an API, and <code>link</code> functions can interact with
controllers using <code>require</code>.</p>
<div class="alert alert-success">
<strong>Best Practice:</strong> use <code>controller</code> when you want to expose an API to other directives.
Otherwise use <code>link</code>.
</div>

<h4 id="creating-custom-directives_demo_summary">Summary</h4>
<p>Here we&#39;ve seen the main use cases for directives. Each of these samples acts as a good starting
point for creating your own directives.</p>
<p>You might also be interested in an in-depth explanation of the compilation process that&#39;s
available in the <a href="guide/compiler">compiler guide</a>.</p>
<p>The <a href="api/ng.$compile"><code><code>$compile</code> API</code></a> page has a comprehensive list of directive options for
reference.</p>
</div></div>
